<% layout('/layouts/default.html', {title: '出库信息目录管理', libs: ['validate','dataGrid']}){ %>
<div class="main-content">
	<div class="box box-main">
		<div class="box-header with-border">
			<div class="box-title">
				<i class="fa icon-note"></i> ${text(ownOutContents.isNewRecord ? '新增出库信息目录' : '编辑出库信息目录')}
			</div>
			<div class="box-tools pull-right">
				<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
			</div>
		</div>
		<#form:form id="inputForm" model="${ownOutContents}" action="${ctx}/own/ownOutContents/save" method="post" class="form-horizontal">
			<div class="box-body">
				<div class="form-unit">${text('基本信息')}</div>
				<#form:hidden path="id"/>
				<div class="row">
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required ">*</span> ${text('企业名称')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="processingName" maxlength="50" class="form-control required"/>
							</div>
						</div>
					</div>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required ">*</span> ${text('出库时间')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="time" readonly="true" maxlength="20" class="form-control Wdate required"
									dataFormat="datetime" onclick="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm',isShowClear:false});"/>
							</div>
						</div>
					</div>
				</div>
				<div class="row">
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required ">*</span> ${text('新货主企业名称')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="newCorpName" maxlength="50" class="form-control required"/>
							</div>
						</div>
					</div>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required ">*</span> ${text('新货主企业编码')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="newCorpCode" maxlength="50" class="form-control required"/>
							</div>
						</div>
					</div>
				</div>
				<div class="row">
					<div class="col-xs-12">
						<div class="form-group">
							<label class="control-label col-sm-2" title="">
								<span class="required hide">*</span> ${text('备注')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-10">
								<#form:textarea path="remarks" rows="4" maxlength="255" class="form-control"/>
							</div>
						</div>
					</div>
				</div>
				<h4 class="form-unit">添加出库的药材信息</h4>
				<div class="ml10 mr10">
					<table id="testDataChildDataGrid"></table>
					<% if (hasPermi('own:ownOutContents:edit') && ownOutContents.isNewRecord){ %>
					<a id="testDataChildDataGridAddRowBtn" class="btn btn-primary btn-sm mt10 mb10" ><i class="fa fa-plus"></i> 增行</a>
					<% } %>
				</div>
			</div>
			<div class="box-footer">
				<div class="row">
					<div class="col-sm-offset-2 col-sm-10">
						<% if (hasPermi('own:ownOutContents:edit')){ %>
							<button type="submit" class="btn btn-sm btn-primary" id="btnSubmit"><i class="fa fa-check"></i> ${text('保 存')}</button>&nbsp;
						<% } %>
						<button type="button" class="btn btn-sm btn-default" id="btnCancel" onclick="js.closeCurrentTabPage()"><i class="fa fa-reply-all"></i> ${text('关 闭')}</button>
					</div>
				</div>
			</div>
		</#form:form>
	</div>
</div>
<% } %>
<script>
	var testDataChild = [];
	$.ajax({
		url: "${ctx}/own/ownOutInformation/findByContentsId?contentsId="+$("#id").val(),
		type: "get",
		dataType: "json",
		success: function(data){
			if (data.result){
				testDataChild = data.data;
				//初始化测试数据子表DataGrid对象
				$("#testDataChildDataGrid").dataGrid({
					data: testDataChild,
					datatype: "local", // 设置本地数据
					autoGridHeight: function(){return 'auto'}, // 设置自动高度

					// 设置数据表格列
					columnModel: [
						{header:'主键', name:'id', editable:true, hidden:true},
						{header:'药材收获ID', name:'ownMedicineReceiptInformationId', editable:true, hidden:true},
						{header:'药材赋码ID', name:'ownMedicineAssignmentId', editable:true, hidden:true},
						/*{header:'药材批次号', name:'batchId', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'200', 'class':'form-control'}},*/
						{header:'药材批次号', name:'batchId', width:150,
							formatter: function(val, obj, row, act){
								return js.val(row, 'batchId');
							}, editable: true, edittype: "custom", editoptions: {
								custom_element: function(val, editOptions) {
									return js.template('listselectTpl', {
										id: editOptions.id, title: '药材批次号',
										name: 'batchId', value: val,
										labelName: 'batchId', labelValue: val,
										url: '${ctx}/own/ownMedicineAssignment/findByKey',
										itemCode: "medicineBatchId",itemName: "medicineBatchId",cssClass:"form-control required"
									});
								}
							}
						},
						{header:'追溯码', name:'bmTraceCode', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'50', 'class':'form-control', 'rows':'1'}},
						{header:'商品编码', name:'sourceCode', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'25', 'class':'form-control', 'rows':'1'}},
						{header:'出库总重量(kg)', name:'weightAll', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'200', 'class':'form-control number', 'rows':'1'}},
						{header:'出库总重量小计(kg)', name:'batchWeightAll', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'200', 'class':'form-control number', 'rows':'1'}},
						{header:'单价(元)', name:'unitprice', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'200', 'class':'form-control number', 'rows':'1'}},
						{header:'合计金额(元)', name:'outBatchAmount', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'200', 'class':'form-control number', 'rows':'1'}},
						{header:'出库对象', name:'outType',  width:150, editable:true, edittype:'text', editoptions:{'maxlength':'25', 'class':'form-control', 'rows':'1'}},
						{header:'规格', name:'spec', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'10', 'class':'form-control', 'rows':'1'}},
						{header:'操作', name:'actions', width:80, sortable:false, fixed:true, formatter: function(val, obj, row, act){
								var actions = [];
								if (val == 'new'){
									actions.push('<a href="#" onclick="js.confirm(\'你确认要删除这条数据吗？\', function(){$(\'#testDataChildDataGrid\').dataGrid(\'delRowData\',\''+obj.rowId+'\')});return false;"><i class="fa fa-trash-o"></i></a>&nbsp;');
								}
								return actions.join('');
							}, editoptions: {defaultValue: 'new'}}
					],

					// 编辑表格参数
					editGrid: true,				// 是否是编辑表格
					editGridInitRowNum: 0,		// 编辑表格的初始化新增行数
					editGridAddRowBtn: $('#testDataChildDataGridAddRowBtn'),	// 子表增行按钮
					editGridAddRowInitData: {},	// 新增行的时候初始化的数据

					// 编辑表格的提交数据参数
					editGridInputFormListName: 'testDataChildList', // 提交的数据列表名
					editGridInputFormListAttrs: '', // 提交数据列表的属性字段

					// 加载成功后执行事件
					ajaxSuccess: function(data){

					}
				});
				close();
				$("#testDataChildDataGridAddRowBtn").click(function (e) {
					close();
				});
			}else {
				js.showErrorMessage("数据查询失败，请重试!");
			}
		},
		error: function(e){
			js.showErrorMessage("错误",e);
		}
	})
</script>
<script id="listselectTpl" type="text/template">//<!--<div>
<#form:listselect id="{{d.id}}" title="{{d.title}}" name="{{d.name}}" value="{{d.value}}"
	labelName="{{d.labelName}}" labelValue="{{d.labelValue}}" url="{{d.url}}"
	itemCode="{{d.itemCode}}" itemName="{{d.itemName}}"
	class="{{d.cssClass}}" btnClass="btn-sm" allowClear="true"/>
</div>//--></script>

<script>
	var childData = [];
	$("#inputForm").validate({
		submitHandler: function(form){
			let ids = $('#testDataChildDataGrid').dataGrid('getDataIDs');
			childData = [];
			for (let id of ids){
				var obj = {
					'id': $('#'+id+'_id').val(),
					'ownMedicineReceiptInformationId': $('#'+id+'_ownMedicineReceiptInformationId').val(),
					'ownMedicineAssignmentId': $('#'+id+'_ownMedicineAssignmentId').val(),
					'batchId': $('#'+id+'_batchIdCode').val(),
					'bmTraceCode': $('#'+id+'_bmTraceCode').val(),
					'sourceCode':$('#'+id+'_sourceCode').val(),
					'weightAll': $('#'+id+'_weightAll').val(),
					'batchWeightAll': $('#'+id+'_batchWeightAll').val(),
					'outType': $('#'+id+'_outType').val(),
					'spec': $('#'+id+'_spec').val(),
					'outBatchAmount': $('#'+id+'_outBatchAmount').val(),
					'unitprice': $('#'+id+'_unitprice').val()
				};
				let temp = false;//判断是否为空对象
				for (let key in obj){
					if (obj[key]){
						temp = true;
						break;
					}
				}
				if (temp){
					childData.push(obj);
				}
			}
			if (childData.length > 0 ){
				var contentsData = {
					"id": $("#id").val(),
					"processingName": $("#processingName").val(),
					"time": $("#time").val(),
					"newCorpName": $("#newCorpName").val(),
					"newCorpCode": $("#newCorpCode").val(),
					"numPackage": childData.length,
					"remarks": $("#remarks").val(),
				}
				for (let index in childData) {
					var item = childData[index];
					contentsData["ownOutInformationList["+index+"].id"]= item["id"];
					contentsData["ownOutInformationList["+index+"].processingName"]= $("#processingName").val();
					contentsData["ownOutInformationList["+index+"].time"]= $("#time").val();
					contentsData["ownOutInformationList["+index+"].newCorpName"]= $("#newCorpName").val();
					contentsData["ownOutInformationList["+index+"].newCorpCode"]= $("#newCorpCode").val();
					contentsData["ownOutInformationList["+index+"].contentsId"]= "";
					contentsData["ownOutInformationList["+index+"].batchId"]= item["batchId"];
					contentsData["ownOutInformationList["+index+"].outType"]= item["outType"];
					contentsData["ownOutInformationList["+index+"].ownMedicineReceiptInformationId"]= item["ownMedicineReceiptInformationId"];
					contentsData["ownOutInformationList["+index+"].ownMedicineAssignmentId"]= item["ownMedicineAssignmentId"];
					contentsData["ownOutInformationList["+index+"].bmTraceCode"]= item["bmTraceCode"];
					contentsData["ownOutInformationList["+index+"].sourceCode"]= item["sourceCode"];
					contentsData["ownOutInformationList["+index+"].weightAll"]= item["weightAll"];
					contentsData["ownOutInformationList["+index+"].batchWeightAll"]= item["batchWeightAll"];
					contentsData["ownOutInformationList["+index+"].spec"]= item["spec"];
					contentsData["ownOutInformationList["+index+"].outBatchAmount"]= item["outBatchAmount"];
					contentsData["ownOutInformationList["+index+"].unitprice"]= item["unitprice"];
				}
				$.ajax({
					url: "${ctx}/own/ownOutContents/save",
					type: "post",
					dataType: "json",
					data: contentsData,
					success: function(data){
						if (data.result && data.data.id){
							js.showMessage("出库成功!");
							js.closeCurrentTabPage(function(contentWindow){
								contentWindow.page();
							});
						}else {
							js.showErrorMessage("出库失败!");
						}
					},
					error: function(e){
						js.showErrorMessage("错误",e);
					}
				})
			}else {
				js.showErrorMessage("请至少添加一项出库信息！");
			}
		}
	});
	//选择药材批次号回调方法
	function  listselectCallback(id, act, index, layero, selectData) {
		if (act == 'ok' || act == 'clear'){
			let temp = id.split("_")[0];
			for (let key in selectData){
				let data = selectData[key];
				$('#'+temp+'_ownMedicineReceiptInformationId').val(data['ownMedicineReceiptInformationId']);
				$('#'+temp+'_ownMedicineAssignmentId').val(data['id']);
				$('#'+temp+'_bmTraceCode').val(data['bmTraceCode']);
				$('#'+temp+'_sourceCode').val(data['sourceCode']);
				$('#'+temp+'_weightAll').val(data['weight']);
				$('#'+temp+'_batchWeightAll').val(data['weight']);
				$('#'+temp+'_outType').val("medicine");
				$('#'+temp+'_spec').val(data['spec']);
				break;
			}
		}
	}
	function close(){
		$("input[name='bmTraceCode']").attr("readonly","readonly");
		$("input[name='sourceCode']").attr("readonly","readonly");
		$("input[name='weightAll']").attr("readonly","readonly");
		$("input[name='batchWeightAll']").attr("readonly","readonly");
		$("input[name='outType']").attr("readonly","readonly");
		$("input[name='spec']").attr("readonly","readonly");
		if("${ownOutContents.isNewRecord}" == "false") {
			$("input[name='batchId']").attr("disabled", "disabled");
			$("input[name='unitprice']").attr("readonly", "readonly");
			$("input[name='outBatchAmount']").attr("readonly", "readonly");
		}
	}
</script>